var fs=require('fs');
var path=require('path');
var https=require("https");
var express = require('express');
var app = express();
const opn = require('opn');
var privateKey  = fs.readFileSync(__dirname+'/ssl/client-key.pem', 'utf8');
var certificate = fs.readFileSync(__dirname+'/ssl/client-cert.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
app.engine('html', require('ejs').renderFile);
app.use(express.static('src'));
app.set('views', './src');

app.get('/', function (req, res) {
    res.render("index");
});

var proxy = require('http-proxy-middleware');

// proxy middleware options
var options = {
    target: 'https://www.us-ebike.com/mobile/app/core', // target host
    changeOrigin: true,               // needed for virtual hosted sites
    //agent:true,
    secure:true,
    pathRewrite: {
        '^/myapi' : '',     // rewrite path
        '^/mobile/app/core' : ''     // rewrite path
    },
    // ssl: {
    //     // pfx:fs.readFileSync(path.join(__dirname, 'ssl/client.p12'),'utf8'),
    //     // passphrase:'123456',
    //     key: fs.readFileSync(path.join(__dirname, 'ssl/key.pem'), 'utf8'),
    //     cert: fs.readFileSync(path.join(__dirname, 'ssl/cert.pem'), 'utf8')
    //     // ,ca:[fs.readFileSync(path.join(__dirname, 'ssl/cacert.pem'), 'utf8')]
    // },
    onError:onError
};

// create the proxy (without context)
var exampleProxy = proxy(options);
app.use('/myapi',exampleProxy);
app.use('/mobile/app/core',exampleProxy);
app.use('/test',function (req,res) {
    res.json({code:0,msg:"ok"})
});
var httpsServer = https.createServer(credentials, app);
httpsServer.listen(3000, function() {
    console.log('HTTPS Server is running on: https://localhost:%s', 3000);
    //打开浏览器
    opn('https://localhost:'+3000+'/?code=xxx&state=xxxx')
});
// var server = app.listen(3000, function () {
//     var host = server.address().address;
//     var port = server.address().port;
//
//     console.log('Example app listening at http://%s:%s', host, port);
//
// });
function onError(e, req, res) {
    console.log(e);
    res.end();
}